package net.yla.smartbus.module.ba.vehicle.service.impl;

import com.github.pagehelper.PageHelper;
import net.yla.smartbus.core.base.PageBean;
import net.yla.smartbus.module.ba.equipment.form.DeviceForm;
import net.yla.smartbus.module.ba.equipment.serice.DeviceService;
import net.yla.smartbus.module.ba.vehicle.common.ExcelData;
import net.yla.smartbus.module.ba.vehicle.detachment.VehicleDetachment;
import net.yla.smartbus.module.ba.vehicle.dto.VehicleDto;
import net.yla.smartbus.module.ba.vehicle.entity.BaVehicleDriverRlDo;
import net.yla.smartbus.module.ba.vehicle.entity.BaVehiclesDo;
import net.yla.smartbus.module.ba.vehicle.form.VehicleForm;
import net.yla.smartbus.module.ba.vehicle.mapper.VehicleMapper;
import net.yla.smartbus.module.ba.vehicle.query.VehicleDeleteQuery;
import net.yla.smartbus.module.ba.vehicle.query.VehicleQuery;
import net.yla.smartbus.module.ba.vehicle.service.VehicleService;
import net.yla.smartbus.module.ba.vehicle.service.VehicleStaffRelevanceService;
import net.yla.smartbus.module.ba.vehicle.utils.FourDate;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 默苍离
 * @date 2021/6/17 16:57
 * <p>
 * ******************************************
 * @annotation:
 */
@Service
public class VehicleServiceImpl implements VehicleService {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private VehicleMapper mapper;

    @Autowired
    private VehicleDetachment vehicleDetachment;

    @Autowired
    private VehicleStaffRelevanceService vehicleStaffRelevanceService;


    /**
     * 根据 查询条件 查询 所有 车辆
     *
     * @param query
     * @return
     */
    @Override
    public List<VehicleDto> getList(VehicleQuery query) {

        List<BaVehiclesDo> list = mapper.getList(query);

        ArrayList<VehicleDto> vehicles = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            BaVehiclesDo vehicle = list.get(i);
            VehicleDto vehicleDto = vehicleDetachment.vehicleDto(vehicle);
            vehicles.add(vehicleDto);
        }

        return vehicles;

    }


    /**
     * 根据 查询条件 查询 所有 车辆的数量
     *
     * @param query
     * @return
     */
    @Override
    public Integer getCount(VehicleQuery query) {
        Integer count = mapper.getCount(query);
        return count;
    }


    /**
     * 根据id查询车辆
     *
     * @param vehicleId
     * @return
     */
    @Override
    public VehicleDto getOne(Integer vehicleId) {
        BaVehiclesDo vehicle = mapper.getOne(vehicleId);
        if (vehicle != null) {
            VehicleDto vehicleDto = vehicleDetachment.vehicleDto(vehicle);
            return vehicleDto;
        }
        return null;
    }


    /**
     * 根据 查询条件 分页查询 所有 车辆
     *
     * @param query
     * @return
     */
    @Override
    public PageBean<VehicleDto> getListByPage(VehicleQuery query) {

        Integer count = getCount(query);
        PageHelper.startPage(query.getPageNum(), query.getPageSize(), "lastModifyTime desc");
        List<VehicleDto> list = getList(query);
        PageBean<VehicleDto> vehicleDtoPageBean = new PageBean<>(list, query.getPageNum(), query.getPageSize(), count);
        return vehicleDtoPageBean;

    }


    /**
     * 删除车辆
     *
     * @param ids
     * @return
     */
    @Override
    public Integer delete(VehicleDeleteQuery ids) {
        Integer delete = mapper.delete(ids.getIds());
        return delete;
    }


    /**
     * 导出车辆
     *
     * @param query
     * @return
     */
    @Override
    public ExcelData exportVehicles(VehicleQuery query) {

        ExcelData excelData = new ExcelData();
        excelData.setFileName("车辆信息");
        List<String> head = new ArrayList<>();
        head.add("机构名称");
        head.add("车牌号");
        head.add("自编号");
        head.add("车辆型号");
        head.add("已安装设备");
        head.add("注册日期");
        head.add("运营类型");
        head.add("车辆行驶证");
        head.add("车辆运营证");
        head.add("车主");

        excelData.setHead(head);
        List<BaVehiclesDo> list = mapper.getList(query);

        List<List<String>> data = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {

            BaVehiclesDo vehicle = list.get(i);
            VehicleDto vehicleDto = vehicleDetachment.vehicleDto(vehicle);
            List<String> content = new ArrayList<>();
            content.add(vehicleDto.getGroupName());
            content.add(vehicleDto.getNo());
            content.add(vehicleDto.getCode());
            content.add(vehicleDto.getModelName());
            List<String> deviceName = vehicleDto.getDeviceName();
            String s = "";
            for (String d : deviceName) {
                s = s + d + ',';
            }
            content.add(s);
            content.add(vehicleDto.getRegistrationDate());
            content.add(vehicleDto.getOperationName());
            content.add(vehicleDto.getDrivingNo());
            content.add(vehicleDto.getOperationNo());
            List<String> ownerName = vehicleDto.getOwnerName();
            String e = "";
            for (String d : ownerName) {
                e = e + d + ',';
            }
            content.add(e);

            data.add(content);
        }
        excelData.setData(data);

        return excelData;

    }


    /**
     * 新增车辆
     *
     * @param form
     * @return
     */
    @Override
    public Integer insert(VehicleForm form) {

        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setNo(form.getNo());
        vehicleQuery.setCode(form.getCode());
        List<VehicleDto> list = getList(vehicleQuery);
        if (list.size() > 0 && form.getVehicleId() == null) {
            return 400;
        }

        form.setInspect1(FourDate.dateToFour(form.getInspect()));
        form.setCompulsory1(FourDate.dateToFour(form.getCompulsory()));
        form.setPersonLiability1(FourDate.dateToFour(form.getPersonLiability()));
        form.setVehicleDamage1(FourDate.dateToFour(form.getVehicleDamage()));

        //车辆照片
        List<String> images = form.getImages();
        if (images != null) {
            for (int i = 0; i < images.size(); i++) {
                switch (i) {
                    case 0:
                        form.setImage1(images.get(i));
                        break;
                    case 1:
                        form.setImage2(images.get(i));
                        break;
                    case 2:
                        form.setImage3(images.get(i));
                        break;
                    case 3:
                        form.setImage4(images.get(i));
                        break;
                    case 4:
                        form.setImage5(images.get(i));
                        break;
                    default:
                }
            }
        }

        if (form.getVehicleId() == null) {
            mapper.insert(form);
        } else {
            mapper.update(form);
        }

        //添加设备信息
        Integer[] deviceId = form.getDeviceId();
        if (deviceId != null) {
            for (int i = 0; i < deviceId.length; i++) {
                DeviceForm deviceForm = new DeviceForm();
                deviceForm.setVehicleId(form.getVehicleId());
                deviceForm.setDeviceId(deviceId[i]);
                deviceService.update(deviceForm);
            }
        }

        //添加人员信息
        Integer[] ownerId = form.getOwnerId();
        if (ownerId != null) {
            for (Integer id : ownerId) {
                BaVehicleDriverRlDo rlDo = new BaVehicleDriverRlDo();
                rlDo.setVehicleId(form.getVehicleId());
                rlDo.setGroupId(form.getGroupId());
                rlDo.setEmpId(id);
                vehicleStaffRelevanceService.insert(rlDo);
            }
        }

        return 1;

    }


    /**
     * 更新车辆信息
     *
     * @param vehicle
     * @return
     */
    @Override
    public Integer update(VehicleForm vehicle) {
        Integer update = mapper.update(vehicle);
        return update;

    }


    /**
     * 通过导入文件新增车辆
     *
     * @param file
     * @return
     */
    @Override
    public Integer insertByImport(MultipartFile file) throws IOException {

        Integer result = 0;

        InputStream inputStream = file.getInputStream();

        //由输入流文件得到工作簿对象
        HSSFWorkbook wb = new HSSFWorkbook(inputStream);
        //获取第一个sheet
        HSSFSheet sheet = wb.getSheetAt(0);
        //获取表格内容的最后一行的行数
        int lastRowNum = sheet.getLastRowNum();

        //rowBegin代表要开始读取的行号，下面这个循环的作用是读取每一行内容
        for (int i = 1; i <= lastRowNum; ++i) {
            VehicleForm excelForm = new VehicleForm();
            //获取每一行
            HSSFRow row = sheet.getRow(i);
            //获取每一行的最后一列的列号，即总列数
            int columnNum = row.getLastCellNum();

            for (int j = 0; j < columnNum; ++j) {
                //获取每个单元格
                HSSFCell cell = row.getCell(j);
                //设置单元格类型
                cell.setCellType(CellType.STRING);
                String cellValue = cell.getStringCellValue();
                if (j == 0) {
                    excelForm.setNo(cellValue);
                }
                if (j == 1) {
                    excelForm.setCode(cellValue);
                }
                if (j == 1) {
                    excelForm.setDrivingNo(cellValue);
                }
                if (j == 1) {
                    excelForm.setOperationNo(cellValue);
                }
            }
            result = insert(excelForm);
        }
        wb.close();
        return result;
    }


}
